import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';
import '../../theme/kq_theme_manager.dart';

class KqChooseDialog extends Dialog {
  //标题
  final String title;

  /// 数据源
  final List<KqChooseData> items;

  ///选中的数据
  final List<String>? chosenIds;

  //是否是多选
  final bool isSingleChoose;

  void Function(void Function()) state;

  /// 回调
  final Function(List<KqChooseData> chooses)? callback;

  KqChooseDialog(
      {Key? key,
      required this.title,
      required this.items,
      required this.state,
      this.chosenIds,
      this.isSingleChoose = true,
      this.callback})
      : super(key: key);

  /// 获取选中的数据
  List<KqChooseData> getChosenData() {
    var chosenData = <KqChooseData>[];
    if (items.isNotEmpty) {
      for (var element in items) {
        if (element.chosen) {
          chosenData.add(element);
        }
      }
    }
    return chosenData;
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> children = <Widget>[];

    int total = items.length;
    // 小诸葛规范，最多显示6个，多余滚动
    var maxHeight = total <= 0
        ? 48.r + 58.r + 16.r
        : (total / 3.0).ceil() >= 6
            ? 48.r * 6 + 58.r + 16.r
            : 48.r * (total / 3.0).ceil() + 58.r + 16.r;
    if (!isSingleChoose) {
      maxHeight = maxHeight + 48.r;
    }

    /// item
    for (int i = 0; i < items.length; i++) {
      var item = items[i];
      Color bgColor = KqThemeColors.bgF5;
      Color txtColor =
          KqThemeManager.instance.getConfig().dialogConfig.titleColor ??
              KqThemeColors.text26;

      if ((chosenIds != null && chosenIds!.isNotEmpty)) {
        if (chosenIds!.contains(item.itemId)) {
          item.chosen = true;
        }
      }
      if (item.chosen) {
        bgColor = KqThemeColors.bgBlue;
        txtColor = KqThemeColors.textWhite;
      }
      children.add(KqInkWell(
        onTap: () {
          //单选
          if (isSingleChoose) {
            if (callback != null) {
              callback!([item]);
            }
          } else {
            state(() {
              item.chosen = !item.chosen;
            });
          }
        },
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(2.r),
            color: bgColor,
          ),
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 12.r),
          child: Text(
            item.name ?? '',
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
            style: TextStyle(color: txtColor, fontSize: 12.sp),
          ),
        ),
      ));
    }

    Widget dialogChild = Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Padding(
          padding:
              EdgeInsets.only(top: 24.r, bottom: 16.r, left: 16.r, right: 16.r),
          child: Text(
            title,
            maxLines: 1,
            style: TextStyle(
                fontSize: 16.sp,
                color: KqThemeColors.text26,
                fontWeight: FontWeight.w600),
          ),
        ),
        Expanded(
          child: GridView.count(
            shrinkWrap: true,
            padding: EdgeInsets.only(left: 11.r, right: 11.r),
            crossAxisSpacing: 8.r,
            mainAxisSpacing: 8.r,
            crossAxisCount: 3,
            childAspectRatio: 47 / 20.0,
            children: children,
          ),
        ),
        SizedBox(
          height: 16.r,
        ),
        if (!isSingleChoose) const KqDivider(),
        if (!isSingleChoose)
          Row(
            children: [
              Expanded(
                  child: KqInkWell(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  height: 48.r,
                  child: Text(
                    KqIntl.currentResource.cancel,
                    style: TextStyle(
                        fontSize: 16.sp,
                        color: KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .cancelBtnColor ??
                            KqThemeColors.text8C),
                  ),
                ),
              )),
              KqVerticalDivider(
                height: 48.r,
              ),
              Expanded(
                  child: KqInkWell(
                onTap: () {
                  if (callback != null) {
                    callback!(getChosenData());
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  height: 48.r,
                  child: Text(
                    KqIntl.currentResource.confirm,
                    style: TextStyle(
                        fontSize: 16.sp,
                        color: KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .mainBtnColor ??
                            KqThemeColors.textLightBlue),
                  ),
                ),
              ))
            ],
          )
      ],
    );
    return UnconstrainedBox(
        child: SizedBox(
            width: 320.r,
            child: Material(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(8.r))),
                color:
                    KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
                        KqThemeColors.bgWhite,
                child: LimitedBox(
                  maxHeight: maxHeight,
                  child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8.r)),
                    child: dialogChild,
                  ),
                ))));
  }
}

class KqChooseData {
  /// 选项标题
  final String? name;

  /// 选项id，非必填
  final String? itemId;

//是否选中
  bool chosen;

  KqChooseData({required this.name, this.itemId, this.chosen = false});
}
